'use strict';

const BaseController = require('./base');
const { success, commonErr } = require('../extend/helper');

class ThemeCommentReplyController extends BaseController {

    /**
     * 列表
     */
    async list() {
        const page = parseInt(this.ctx.query.page) ? parseInt(this.ctx.query.page) : 0;
        const size = parseInt(this.ctx.query.size) ? parseInt(this.ctx.query.size) : 15;
        const where = await this.where();
        const { rows, count } = await this.ctx.model.ThemeCommentReply.findAndCountAll({
            include: [
                {
                    model: this.ctx.model.User,
                    as: "user",
                    attributes: ['id', 'nickname']
                },
                {
                    model: this.ctx.model.User,
                    as: "reply_user",
                    attributes: ['id', 'nickname']
                },
            ],
            where: where,
            order: [
                ['create_time', 'desc']
            ],
            offset: page * size,
            limit: size
        });
        success({
            beans: {
                rows, count, page, size

            }
        })

    }
    
    async where() {
        const commentId = this.ctx.query.comment_id;
        const userId = this.ctx.query.user_id;
        const replyUserId = this.ctx.query.reply_user_id;
        const online =  this.ctx.query.online;
        const where = {};
        if (commentId) {
            where.comment_id = commentId;
        }
        if (userId) {
            where.user_id = userId;
        }
        if (replyUserId) {
            where.reply_user_id = replyUserId;
        }
        if (online == 'true') {
            where.online = true;
        } 
        if (online == 'false') {
            where.online = false;
        }
        return where;
    }

    /**
     * 删除
     */
    async delete() {
        const reply = await this.getObject();
        reply.destroy();
        success();
    }

    /**
     * 切换显示按钮
     */
    async online() {
        const reply = await this.getObject();
        await this.onlineSwitch(reply);
        success();
    }


    async getObject() {
        const id = this.ctx.params.id;
        const reply = await this.ctx.model.ThemeCommentReply.findByPk(id);
        if (!reply) {
            commonErr(`回复不存在`);
        }
        return reply;
    }

}

module.exports = ThemeCommentReplyController;
